﻿using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
using Netduino.Modules.PeteBrown;
using PeteBrown.MidiUtilities;

namespace Netduino.MidiLoopbackTest
{
    public class Program
    {
        private static byte _note = MidiUtility.A440NoteNumber;
        private static byte _velocity = 127;
        private static MidiChannel _channel = MidiChannel.Channel01;

        private static MidiModule _midi;
        private static InterruptPort _button1;

        public static void Main()
        {
            // RX on Netduino Pin 2, TX on Pin 3
            _midi = new MidiModule(SerialPorts.COM2);

            _midi.MessageReceived += OnMidiMessageReceived;
            _midi.EnableReceiver();

            _button1 = new InterruptPort(Pins.ONBOARD_SW1, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
            _button1.OnInterrupt += OnButton1Pressed;

            Thread.Sleep(Timeout.Infinite);
        }

        static void OnButton1Pressed(uint data1, uint data2, DateTime time)
        {
            Debug.Print("Button 1 Pressed.");
            _midi.SendNoteOn(_channel, _note, _velocity);
            Debug.Print("MIDI Message Sent ============== ");
        }

        static void OnMidiMessageReceived(MidiModule sender, MidiMessageRecievedEventArgs args)
        {
            Debug.Print("MIDI Message Received ============== ");

            if (args.Message.Channel != _channel)
                Debug.Print("Incorrect Channel Received: " + args.Message.Channel);
            else
                Debug.Print("Correct channel received.");

            if (args.Message.DataByte1 != _note)
                Debug.Print("Incorrect note received: " + args.Message.DataByte1);
            else
                Debug.Print("Correct note received.");

            if (args.Message.DataByte2 != _velocity)
                Debug.Print("Incorrect velocity received: " + args.Message.DataByte2);
            else
                Debug.Print("Correct velocity received.");            
        }

    }
}
